<template>
  <el-container>
    <el-aside width="250px">
      <!-- 新增“新增菜单”按钮 -->
      <div style="padding: 10px;">
        <el-button type="primary" @click="openAddDialog">新增菜单</el-button>
      </div>
      <el-menu :default-openeds="['2', '4']" :default-active="activeMenu" mode="inline">
        <template v-for="(menu, index) in menuList" :key="index">
          <el-sub-menu v-if="hasChildren(menu)" :index="menu.id + ''">
            <template #title>
              <i :class="menu.icon"></i>
              <span>{{ menu.title }}</span>
            </template>
            <el-menu-item
              v-for="subMenu in menu.children"
              :key="subMenu.id"
              :index="subMenu.id + ''"
              @click="handleMenuClick(subMenu)"
            >
              {{ subMenu.title }}
              <div class="menu-buttons">
                <el-button type="text" icon="el-icon-edit" @click.stop="handleEdit(subMenu)"
                  >编辑</el-button
                >
                <el-button
                  type="text"
                  icon="el-icon-delete"
                  text-color="red"
                  @click.stop="handleDelete(subMenu)"
                  >删除</el-button
                >
              </div>
            </el-menu-item>
          </el-sub-menu>
          <el-menu-item v-else :index="menu.id + ''" @click="handleMenuClick(menu)">
            <i :class="menu.icon"></i>
            <span>{{ menu.title }}</span>
            <div class="menu-buttons">
              <el-button type="text" icon="el-icon-edit" @click.stop="handleEdit(menu)"
                >编辑</el-button
              >
              <el-button
                type="text"
                icon="el-icon-delete"
                text-color="red"
                @click.stop="handleDelete(menu)"
                >删除</el-button
              >
            </div>
          </el-menu-item>
        </template>
      </el-menu>
    </el-aside>
    <el-main>
      <router-view></router-view>
    </el-main>
    <!-- 新增菜单弹窗 -->
    <el-dialog v-model="addDialogVisible" :title="addDialogTitle" width="400px">
      <el-form :model="addForm" label-width="80px">
        <el-form-item label="父级菜单">
          <el-select v-model="addForm.pid" placeholder="选择父级菜单">
            <!-- 筛选出 pid=0 的菜单作为父级选项 -->
            <el-option
              v-for="menu in parentMenuOptions"
              :key="menu.id"
              :label="menu.title"
              :value="menu.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="权限">
          <el-select v-model="addForm.role" placeholder="选择权限">
            <el-option label="老师" value="2"></el-option>
            <el-option label="超级管理员" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="菜单名称">
          <el-input v-model="addForm.title" placeholder="输入菜单名称"></el-input>
        </el-form-item>
        <el-form-item label="菜单路由">
          <el-input v-model="addForm.route" placeholder="输入菜单路由"></el-input>
        </el-form-item>
        <!-- 若有其他字段（如route、icon等），可继续添加表单项 -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAdd">确认添加</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 编辑弹窗 -->
    <el-dialog v-model="editDialogVisible" :title="editDialogTitle" width="400px">
      <el-form :model="editForm" label-width="80px">
        <el-form-item label="菜单ID">
          <el-input v-model="editForm.id" disabled></el-input>
        </el-form-item>
        <el-form-item label="父级菜单">
          <el-input v-model="editForm.pidName" disabled></el-input>
        </el-form-item>
        <el-form-item label="菜单标题">
          <el-input v-model="editForm.title"></el-input>
        </el-form-item>
        <!-- 若有其他字段（如route、icon等），可继续添加表单项 -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveEdit">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </el-container>
</template>

<script setup>
import { onMounted, ref, computed } from 'vue'
import { ElMessage, ElButton } from 'element-plus'
import api from '@/api/Menu'
import { TeacherInfo } from '@/stores/counter'
import { useRouter } from 'vue-router'

const userStore = TeacherInfo()
const router = useRouter()
const menuList = ref([])
const activeMenu = ref('1')

// 新增菜单弹窗相关响应式数据
const addDialogVisible = ref(false)
const addDialogTitle = ref('新增菜单')
const addForm = ref({
  pid: 0, // 默认选 pid=0 的父级菜单，也可根据需求调整
  role: '',
  title: ''
})

// 编辑弹窗相关响应式数据
const editDialogVisible = ref(false)
const editDialogTitle = ref('编辑菜单')
const editForm = ref({
  id: '',
  pidName: '',
  title: ''
})

// 检查菜单是否有子菜单
const hasChildren = (menu) => {
  return menu.children && menu.children.length > 0
}

// 加载菜单列表
const loadMenus = async () => {
  try {
    const res = await api.findMenus(userStore.teacherinfo.teacherName)
    menuList.value = res || []
  } catch (error) {
    console.error('获取菜单失败：', error)
    ElMessage.error('菜单加载失败，请重试')
  }
}

// 父级菜单选项（筛选出 pid=0 的菜单）
const parentMenuOptions = computed(() => {
  return menuList.value.filter(menu => menu.pid === 0)
})

// 处理菜单点击事件
const handleMenuClick = (menu) => {
  ElMessage.success(`点击了菜单：${menu.title}`)
  // 这里可添加实际的路由跳转逻辑，比如
  // router.push(menu.route);
}

// 打开新增菜单弹窗
const openAddDialog = () => {
  addForm.value = {
    pid: 0,
    role: '',
    title: ''
  }
  addDialogVisible.value = true
}

// 处理新增菜单保存事件
const saveAdd = async () => {
  try {
    console.log('提交新增菜单数据：', addForm.value)
    const res = await api.insertMenu(addForm.value)
    if (res.code === 200) {
      ElMessage.success('菜单新增成功！')
      addDialogVisible.value = false
      // await loadMenus() 
      window.location.reload(); 
    } else {
      throw new Error('菜单新增失败，请重试')
    }
  } catch (error) {
    console.error('新增菜单失败：', error)
    ElMessage.error('菜单新增失败，请重试')
  }
}

// 处理编辑事件：弹出对话框并回显数据
const handleEdit = (menu) => {
  editForm.value.id = menu.id
  const parentMenu = menuList.value.find((item) => item.id === menu.pid)
  editForm.value.pidName = parentMenu ? parentMenu.title : '无父级（一级菜单）'
  editForm.value.title = menu.title
  editDialogVisible.value = true
}

// 处理保存编辑事件（可根据实际需求调用接口更新）
const saveEdit = async () => {
  try {
    console.log('提交编辑数据：', editForm.value)
    const res = await api.editMenu(editForm.value)
    if (res.code === 200) {
      ElMessage.success('菜单编辑成功！')
      editDialogVisible.value = false
      // await loadMenus() 
      window.location.reload(); 
    } else {
      throw new Error('菜单编辑失败，请重试')
    }
  } catch (error) {
    console.error('编辑菜单失败：', error)
    ElMessage.error('菜单编辑失败，请重试')
  }
}

// 处理删除事件
const handleDelete = async (menu) => {
  try {
    // 等待删除接口完成
    await api.deleteMenu({ id: menu.id }); 
    ElMessage.success(`删除菜单:ID=${menu.id}，标题=${menu.title}，成功！`);
    // 重新加载菜单
    // await loadMenus(); 
    window.location.reload(); 
  } catch (error) {
    console.error('删除菜单失败：', error);
    ElMessage.error('菜单删除失败，请重试');
  }
}

// 页面加载时加载菜单
onMounted(() => {
  loadMenus()
})
</script>

<style scoped>
/* 调整按钮样式 */
.menu-buttons {
  display: inline-block;
  margin-left: 10px;
}

.el-menu-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>